package com.x.wcrm.assemble.control.jaxrs.contactsopportunity;

import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.annotation.CheckPersistType;
import com.x.base.core.entity.annotation.CheckRemoveType;
import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.http.WrapOutId;
import com.x.base.core.project.tools.ListTools;
import com.x.wcrm.assemble.control.Business;
import com.x.wcrm.core.entity.Contacts;
import com.x.wcrm.core.entity.ContactsAndOpportunity;
import com.x.wcrm.core.entity.Opportunity;

import java.util.List;

public class ActionDelete extends BaseAction {

	ActionResult<WrapOutId> execute(EffectivePerson effectivePerson, String contactsid,String opportunityid) throws Exception {
		try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
			ActionResult<WrapOutId> result = new ActionResult<>();
			Business business = new Business(emc);
			Contacts contacts = emc.find(contactsid, Contacts.class);
			if (null == contacts) {
				throw new ExceptionEntityNotExist(contactsid, Contacts.class);
			}
			Opportunity opportunity = emc.find(opportunityid, Opportunity.class);
			if (null == opportunity) {
				throw new ExceptionEntityNotExist(opportunityid, Opportunity.class);
			}

			List<ContactsAndOpportunity> os =  business.contactsAndOpportunityFactory().getOne_By_OpportunityId_And_ContactsId(opportunityid,contactsid);

			if (ListTools.isEmpty(os)) {
				throw new ExceptionEntityNotExist(opportunityid, ContactsAndOpportunity.class);
			}
			ContactsAndOpportunity o = os.get(0);
			emc.beginTransaction(ContactsAndOpportunity.class);
			emc.remove(o, CheckRemoveType.all);
			emc.commit();
			WrapOutId wo = new WrapOutId(o.getId());
			result.setData(wo);
			return result;
		}
	}

}

